package com.xiyue.leaspring.config;

import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import java.util.Collection;
import java.util.Iterator;

/**
 * 描述
 *
 * @author xiyue
 * @version 1.0
 * @date 2021/04/19 22:28:38
 */
public class IPAdressVoter implements AccessDecisionVoter<Object> {

    private static final String LOCAL_FLAG = "LOCAL_IP";//需要判断的访问标记

    @Override
    public boolean supports(ConfigAttribute attribute) {//如果有指定配置属性，则执行投票器
        return attribute!=null &&
                attribute.toString().contains(LOCAL_FLAG);
    }

    @Override
    public boolean supports(Class<?> clazz) {//对所有访问类均支持投票
        return true;
    }

    @Override
    public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
        if(!(authentication.getDetails() instanceof WebAuthenticationDetails)){//如果不是来自Web访问
            return AccessDecisionVoter.ACCESS_DENIED;//拒绝该用户访问
        }
        //通过认证信息获取用户的详情内容,该内容类型WebAuthenticationDetails
        WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
        String ip = details.getRemoteAddress();//取得当前操作的IP地址
        Iterator<ConfigAttribute> iterator = attributes.iterator();//获取每一个配置属性
        while (iterator.hasNext()){//循环每一个配置属性
            ConfigAttribute configAttribute = iterator.next();//获取属性
            if(configAttribute.toString().contains(LOCAL_FLAG)){//如果在本地执行
                if("0:0:0:0:0:0:0:1".equals(ip) || "127.0.0.1".equals(ip)){//本地访问
                    return AccessDecisionVoter.ACCESS_GRANTED;//访问通过
                }
            }
        }
        return AccessDecisionVoter.ACCESS_ABSTAIN;//弃权不参与投票
    }
}
